//
//  ZHMovableBackgroundView.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/3/6.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class ZHMovableBackgroundView: NSView {
    
    let _mouseDragDetectionThreshold:CGFloat = 1
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
   
    override func mouseDown(with event: NSEvent) {
        self._mouseDragged(with: event)
    }
    func _mouseDragged(with event: NSEvent) {
        
        let window = self.window!
        let whereRect = window.convertToScreen(NSMakeRect(event.locationInWindow.x, event.locationInWindow.y, 1, 1))
        var wherePoint = NSMakePoint(whereRect.origin.x, whereRect.origin.y)
        var origin = window.frame.origin
        var deltaX:CGFloat = 0.0
        var deltaY:CGFloat = 0.0
        let appsEvent = NSApp.nextEvent(matching: [NSEvent.EventTypeMask.leftMouseDown,NSEvent.EventTypeMask.leftMouseDragged,NSEvent.EventTypeMask.leftMouseUp], until: Date.distantFuture, inMode: RunLoop.Mode.eventTracking, dequeue: true)
        
        while (event==appsEvent) && (event.type != NSEvent.EventType.leftMouseUp){
            let nowRect = window.convertToScreen(NSMakeRect(event.locationInWindow.x, event.locationInWindow.y, 1, 1))
            let now = NSMakePoint(nowRect.origin.x, nowRect.origin.y)
            deltaX+=now.x-wherePoint.x
            deltaY+=now.y-wherePoint.y
            if (abs(deltaX) >= _mouseDragDetectionThreshold) ||
                (abs(deltaY) >= _mouseDragDetectionThreshold){
                origin.x+=deltaX
                origin.y+=deltaY
                window.setFrameOrigin(origin)
                deltaX = 0
                deltaY = 0
            }
            wherePoint = now
        }
    }
    
    
}
